package TechStuff;

import java.rmi.RemoteException;
import java.util.List;

import Controllers.GameController;
import Controllers.GameControllerInterface;
import Models.GameModel;
import Models.Player;
import Models.Point2D;
import Models.StandardPlayer;

public class Server implements ServerInterface {
	private ClientInterface player1;
	private ClientInterface player2;
	private GameModel game;
	private boolean lock = false;
	private GameControllerInterface gameController = new GameController();
	
	

	@Override
	public int registerClient() throws RemoteException {
		if(player1 == null && !lock)	
		{
			lock = true;
			return 1;
		}
		else if(player2 == null && !lock)
		{
			lock = true;
			return 2;
		}
		else
			return -1;
	}

	@Override
	public void createClient(int id) throws RemoteException {
		
		if(id == 1 && lock)
		{
			lock = false;
			player1 = new ClientStub(id);
		}
		else if(id == 2 && lock)
		{
			lock = false;
			player2 = new ClientStub(id);
		}
		else 
			 System.err.println("Cannot create client with id -1");
	}

	@Override
	public void unregisterClient(int id) throws RemoteException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean movePiece(Point2D from, Point2D to, int id)
			throws RemoteException {
		
		List<Player> players = game.getPlayers();
		
		int indexOfCurrent = players.indexOf(game.getCurrentPlayer());
		
		if (indexOfCurrent + 1 == id) {
			if (gameController.movePiece(from, to, game)) {
				player1.piceMoved(from, to);
				player2.piceMoved(from, to);
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
			
		
		
	}

	@Override
	public void resetGame() throws RemoteException {
		game = GameController.getNew(new StandardPlayer(), new StandardPlayer());
		
	}
}
